
# 编程实现：循环输入10个人的信息（姓名，年龄，性别，身高），并存储到数据库中

import pymysql

db = pymysql.connect(
    host = 'localhost',
    user = 'root',
    password = '123456',
    database = 'sqlope',
    port = 3306,
    charset = 'utf8'
)

try:
    with db.cursor() as cursor:
        cursor.execute("show tables like 'person'")
        if not cursor.fetchone():
            data = "username varchar(20),age int,sex char(4),high double(3,2)"
            sql = f"create table person({data})"
            cursor.execute(sql)
            db.commit()
            print("表创建成功")
        for i in range(1,11):
            name = input(f"请输入第{i}人姓名：")
            age = int(input(f"请输入第{i}人年龄："))
            sex = input(f"请输入第{i}人性别：")
            high = float(input(f"请输入第{i}人身高（两位小数）："))
            sql2 = f"insert into person values(%s,%s,%s,%s)"
            cursor.execute(sql2,(name,age,sex,high))
            db.commit()
            print("数据添加成功")
except Exception as e:
    print("数据添加失败",e)
finally:
    db.close()



